package com.ctshk.rpc.order.goods.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.order.goods.dto.WriteOffRecordPageListDTO;
import com.ctshk.rpc.order.goods.entity.Order;
import com.ctshk.rpc.order.goods.entity.WriteOffRecord;
import com.ctshk.rpc.order.goods.mapper.OrderMapper;
import com.ctshk.rpc.order.goods.mapper.WriteOffRecordMapper;
import com.ctshk.rpc.order.goods.req.OrderPageListPageReq;
import com.ctshk.rpc.order.goods.req.WriteOffRecordReq;
import com.ctshk.rpc.order.goods.service.IWriteOffRecordService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 核销记录表 服务实现类
 * </p>
 *
 * @author 姜斌文
 * @since 2021-04-29
 */
@DubboService
public class WriteOffRecordServiceImpl extends ServiceImpl<WriteOffRecordMapper, WriteOffRecord> implements IWriteOffRecordService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WriteOffRecordMapper writeOffRecordMapper;
    @Override
    public void orderWriteOff(WriteOffRecordReq req, TokenUser tokenUser) {
        if (null == req || null == req.getOrderNumberId() || null == req.getWriteOffNumber()){
            throw new BusinessException(SystemError.SYS_402);
        }
        if (null == tokenUser) {
            throw new BusinessException(SystemError.SYS_406);
        }
        LocalDateTime now = LocalDateTime.now();
        Order order = orderMapper.selectById(req.getOrderNumberId());
        if (order.getWriteOffStatus() == 2 || null != order.getWriteOffTime()){
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23029);
        }
        if (!order.getOrderWriteOffNumber().equals(req.getWriteOffNumber())){
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23030);
        }

        WriteOffRecord writeOffRecord = new WriteOffRecord();
        BeanUtils.copyProperties(req, writeOffRecord);
        if (writeOffRecord.getWriteOffUserId() == null) {
            writeOffRecord.setWriteOffUserId(tokenUser.getId());
            writeOffRecord.setWriteOffUserName(tokenUser.getUsername());
        }
        writeOffRecord.setWriteOffOrderNumber(generateWriteOffOrderNumber(now));
        writeOffRecord.setOrderNumberId(order.getId());
        writeOffRecord.setOrderNumber(order.getOrderNumber());
        writeOffRecord.setWriteOffType(2); // 核销类型：1-商品核销(该核销方式暂时不做)；2-订单核销
        writeOffRecord.setWriteOffTime(now);
        writeOffRecord.setWriteOffNumber(order.getOrderWriteOffNumber());
        writeOffRecord.setCreateId(tokenUser.getId());
        writeOffRecord.setGmtCreate(now);
        writeOffRecord.setModifiedId(tokenUser.getId());
        writeOffRecord.setGmtModified(now);
        writeOffRecord.setIsDeleted(IsDeletedCode.NO.getCode());
        writeOffRecordMapper.insert(writeOffRecord);
    }

    @Override
    public PageResponse<WriteOffRecordPageListDTO> orderWriteOffRecordPageList(OrderPageListPageReq req, TokenUser currentUser) {
        IPage<WriteOffRecordPageListDTO> page = new Page<WriteOffRecordPageListDTO>(req.getPageNo(),req.getPageSize());
        IPage<WriteOffRecordPageListDTO> iPage = writeOffRecordMapper.findWriteOffRecordPageByCondition(page, req);
        List<WriteOffRecordPageListDTO> recordsList = iPage.getRecords();
        List<WriteOffRecordPageListDTO> pageDTOList = EntityUtil.copyList(recordsList, WriteOffRecordPageListDTO.class);
        return new PageResponse<>(pageDTOList, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    /**
     * 生成核銷單號：年月日+三位随机数(沟通后的方式)
     * @param now 日期
     * @return 单号
     */
    private String generateWriteOffOrderNumber(LocalDateTime now) {
        //生成规则：S+部門代碼+員工編號+年後2位+月日4位+3位隨機數字
        StringBuffer sb = new StringBuffer();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        String localTime = df.format(now);
        sb.append(localTime);
        // 最后生成3位随机数，没有硬性要求，000-999，故取了100-999
        Random random = new Random();
        int s = random.nextInt(999)%(999-100+1) + 100;
        sb.append(s);
        return  sb.toString();
    }
}
